package com.cuit.utils;

import org.apache.commons.dbcp.BasicDataSource;

import javax.sql.DataSource;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class JDBCUtils {
    public static String drivername;
    public static String url;
    public static String user;
    public static String password;

    // 创建连接池
    private static BasicDataSource dataSource = new BasicDataSource();

    static {
        Properties properties = new Properties();
        try {
            FileReader fileReader = new FileReader("db.properties");
            properties.load(fileReader);

            drivername = properties.getProperty("drivername");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");

            // Class.forName(drivername);
            dataSource.setDriverClassName(drivername);
            dataSource.setUrl(url);
            dataSource.setUsername(user);
            dataSource.setPassword(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 返回连接池对象
    public static DataSource getDataSource() {
        return dataSource;
    }

    public static Connection getConnection() throws Exception {
        return DriverManager.getConnection(url, user, password);
    }

}
